<?php
namespace Back\Controller;
use Think\Controller;
use Think\Image;
use Think\Page;
use Think\Upload;

/**
 * 品牌管理控制器
 * @package Back\Controller
 */
class GoodsController extends Controller
{
    /**
     * 批量处理
     */
    public function multiAction()
    {
        $operate = 'delete'; // 默认的动作
        // 判断是否传递了selected中
        $selected = I('post.selected', []);
        if (empty($selected)) {
            // 没有任何的主键值
            // 不需要完成操作
            $operate = '';
        }
        // 有可用的主键值
        // 判断当前的操作类型
        switch ($operate) {
            case 'delete':
                // in条件删除即可
                M('Goods')->where(['goods_id'=>['in', $selected]])->delete();
                break;
        }
        $this->redirect('list');
    }

    /**
     * 设置, 添加修改
     */
    public function setAction()
    {

        if (IS_POST) {
            // 获取PK, 核心判断依据
            $goods_id = I('post.goods_id', '');
            // 获取模型
            $model = D('Goods');
            // 创建数据, 触发 验证, 填充
            if ($model->create()) {
                // 如果创建成功, 则插入或更新数据
                if ($goods_id === '') {
                    // 添加
                    $model->add();
                } else {
                    $model->save();
                }
                //维护分类与商品的关联
                $model_category_goods=M('CategoryGoods');
                //先删除原来的关联
                $model_category_goods->where(['goods_id'=>$goods_id])->delete();
                //插入新关联
                $category_id_list=I('post.category_id',[]);
                if(!empty($category_id_list)){
                    $rows=array_map(function($category_id) use ($goods_id){
                        return [
                          'category_id'=>$category_id,
                            'goods_id' =>$goods_id,
                        ];
                    },$category_id_list);
                    $model_category_goods->addAll($rows);
                }
                //商品相册管理
                $model_gallery = D('Gallery');

                foreach (I('post.galleries',[]) as $row){
                    $row['goods_id'] =$goods_id;
                    if($model_gallery->create($row)){
                        if(isset($row['gallery_id'])){
                            $model_gallery->save();
                        }else{
                            $model_gallery->add();
                        }
                    }
                }
                // 成功, 回到列表
                $this->redirect('list');
            } else {
                // 错误信息与出错的数据,记录在session中
                session('message', $model->getError());
                session('data', I('post.'));
                // 重定向
                $param = [];
                if($goods_id !== '') {
                    $param['goods_id'] = $goods_id;
                }
                $this->redirect('set', $param);
            }

        } else {
            // 获取goods_id, 核心判断依据
            $goods_id = I('get.goods_id', '');
            // 获取消息
            $message = session('message');
            // 不需要了, 立即删除
            session('message', null);
            // 分配到模板
            $this->assign('message',  $message ? $message : []);

            // 原始错误数据
            $data = session('data');
            session('data', null);
            // 如果session中的出错数据存在, 则不需要通过goods_id
            // 在数据表中查询
            if ($goods_id && !$data) {
                // 根据ID获取数据
                $data = M('Goods')->find($goods_id);
            }
            $this->assign('data', $data ? $data : []);
             //库存单位
            $this->assign('sku_list',M('Sku')->order('sort_number')->select());
            //税类型
            $this->assign('tax_list',M('Tax')->order('sort_number')->select());

            //库存状态
            $this->assign('stock_status_list',M('StockStatus')->order('sort_number')->select());
            //长度单位
            $this->assign('length_unit_list',M('LengthUnit')->order('sort_number')->select());
           //重量单位
            $this->assign('weight_unit_list',M('WeightUnit')->order('sort_number')->select());
            //品牌列表
            $this->assign('brand_list',M('Brand')->order('sort_number')->select());
            //分类列表
            $this->assign('category_list',D('Category')->getTree());

            //关联表
            $this->assign('category_linked',M('CategoryGoods')->where(['goods_id'=>$goods_id])->
            getField('category_id',true));

            $this->assign('gallery_list',M('Gallery')->where(['goods_id'=>$goods_id])->select());
            // 显示编辑页面
            $this->display();
        }

    }
    /**
     * 列表
     */
    public function listAction()
    {
        $model = M('Goods');

        // 条件部分
        $cond = []; // 默认条件
        $filter = [];
        // 再次分配到模板
        $this->assign('filter', $filter);


        // 排序部分
        // 判断用户是否传递了 排序, 否则使用默认值(保证每个表都有sort_number)
        $sort['field'] = I('get.field', 'sort_number');
        $sort['type'] = I('get.type', 'asc');
        // 拼凑好的排序字符串
        $order = "`{$sort['field']}` {$sort['type']}";
        // 将当前的排序方式, 分配模板中
        $this->assign('sort', $sort);

        // 分页查询
        // 每页显示的记录数
        $limit = 5;
        // 获取总记录数量
        $total = $model->where($cond)->count();

        // 获取分页Page对象
        $page = new Page($total, $limit);

        // 完成查询
        $rows = $model
                ->where($cond)
                ->order($order)
                ->limit($page->firstRow . ', ' . $limit)
                ->select();
        $this->assign('rows', $rows);

        // 获取翻页的HTML代码
        // 配置显示
        $page->setConfig('header', '显示开始 %PAGE_START% 到 %PAGE_END% 之 %TOTAL_ROW% (总 %TOTAL_PAGE% 页)');
        $page->setConfig('theme', '<div class="col-sm-6 text-left"><ul class="pagination">%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%</ul></div> <div class="col-sm-6 text-right">%HEADER%</div>');
        $page->setConfig('prev', '<');
        $page->setConfig('next', '>');
        $page->setConfig('first', '|<');
        $page->setConfig('last', '>|');

        $page_html = $page->show();
        $this->assign('page_html', $page_html);

        $this->display();
    }




    /**
     * ajax操作
     */
    public function checkAction()
    {
        $field=I('request.field');
        switch ($field){
            case 'sku_id':
                echo D('Goods')->checkSkuId(I('request.sku_id')) ? 'true' : 'false';
                break;
        }
    }
    //ajax文件上传

   public function uploadAction(){
        $type=I('request.type','goods');
        $upload= new Upload();
        //不同逻辑的图像，使用配置不同
        switch ($type){
            case 'description':
            case 'goods':
                $upload->savePath='Goods/';
                $name='image';
                break;

            case 'gallery':
                $upload->savePath = 'Gallery/';// 指定的上传逻辑子目录
                $name = 'galleries';
                break;


        }
        //配置工具合理的参数
        $upload->rootPath='./Upload/';//上传的根目录
        $upload->exts=['gif','jpeg','png','jpg'];
        $upload->maxSize = 1*1024*1024;//1M
        $info= $upload->uploadOne($_FILES[$name]);//上传

        if($info){
            //上传成功后
            //记录上传的图形数据，在返回值中
            $data['error']=0;
            $data['image']=$info['savepath'].$info['savename'];
            //制作缩略图
            $image =new Image();
            //打开需要处理的图像
            $image->open($upload->rootPath.$info['savepath'].$info['savename']);
            //保存
            $thumb_root='./Public/Thumb/';
            $save_path=date('Y-m-d').'/';
            if(!is_dir($thumb_root.$save_path)){
                mkdir($thumb_root.$save_path);
            }
            switch ($type){
                case 'goods' :
            $image->thumb(CG('goods_image_width',263),CG('goods_image_height',298),Image::IMAGE_THUMB_FILLED);
                $image->save($thumb_root.$save_path.$info['savename']);
            //记录缩略图信息
                $data['image_thumb']=$save_path.$info['savename'];
                break;
                case 'gallery':
                    $image->thumb(CG('gallery_big_width',800),CG('gallery_big_height',800),Image::IMAGE_THUMB_FILLED);
                    $image->save($thumb_root.$save_path.'big-'.$info['savename']);

                    $image->thumb(CG('gallery_medium_width',300),CG('gallery_medium_height',300),Image::IMAGE_THUMB_FILLED);
                    $image->save($thumb_root.$save_path.'medium-'.$info['savename']);

                    $image->thumb(CG('gallery_small_width',60),CG('gallery_small_height',60),Image::IMAGE_THUMB_FILLED);
                    $image->save($thumb_root.$save_path.'small-'.$info['savename']);

                    //记录缩略图信息
                $data['image_big']=$save_path.'big-'.$info['savename'];
                $data['image_medium']=$save_path.'medium-'.$info['savename'];
                $data['image_small']=$save_path.'small-'.$info['savename'];
                break;
            }


        }else{
            $data['error']=1;
            $data['errorInfo']=$upload->getError();
        }
        $this->ajaxReturn($data);
    }

    //删除相册图像

    public function  removeAction(){
       //接收请求消息
        $gallery_id=I('request.gallery_id',null);
        $image_small = I('request.image_small',null);

        //删除相册有关的资源
       if(!is_null($gallery_id)){

           $model=M('Gallery');

           //查询删除的相册id
           $model->find($gallery_id);
           @unlink('./Upload/'.$model->image);
           @unlink('./Public/Thumb/'.$model->image_small);
           @unlink('./Public/Thumb/'.$model->image_medium);
           @unlink('./Public/Thumb/'.$model->image_big);


           $model->delete();


       }
        if(!is_null($image_small)){
            @unlink('./Public/Thumb/'.$image_small);
            @unlink('./Public/Thumb/'.str_replace('small-','medium-',$image_small));
            @unlink('/Public/Thumb/'.str_replace('small-','big-',$image_small));
            @unlink('/Public/Thumb/'.str_replace('small-','',$image_small));
        }
        $this->ajaxReturn(['error'=>0]);


    }
}